//
//  SoundNotifier.m
//  Cidney
//
//  Created by Chris Karr on 1/12/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "SoundNotifier.h"
#import "Caller.h"
#import "Dispatcher.h"
#import "FilterManager.h"
#import <AddressBook/AddressBook.h>

@implementation SoundNotifier

@synthesize sound;

- (void) awakeFromNib
{
	self.sound = [NSSound soundNamed:@"Phone"];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:FILTERED_CALL object:nil];
}

- (void) update: (NSNotification *) msg
{
	NSSound * thisSound = self.sound;
	
	NSDictionary * userInfo = [msg userInfo];
	
	ABPerson * person = [userInfo valueForKey:PERSON_KEY];
	
	if (person != nil)
	{
		NSString * soundName = [person valueForProperty:SOUND_PROPERTY];
		
		if (soundName != nil)
			thisSound = [NSSound soundNamed:soundName];
	}
		
	if (![thisSound isPlaying] && [[NSUserDefaults standardUserDefaults] boolForKey:RINGTONES])
		[thisSound play];
}

- (NSArray *) sounds
{
	NSMutableSet * soundFiles = [NSMutableSet set];
	
	NSFileManager * fm = [NSFileManager defaultManager];
	
	for (NSString * file in [fm directoryContentsAtPath:@"/Library/Sounds"])
	{
		if (![file isEqualToString:@".DS_Store"])
			[soundFiles addObject:[file stringByDeletingPathExtension]];
	}

	for (NSString * file in [fm directoryContentsAtPath:@"/System/Library/Sounds"])
	{
		if (![file isEqualToString:@".DS_Store"])
			[soundFiles addObject:[file stringByDeletingPathExtension]];
	}

	for (NSString * file in [fm directoryContentsAtPath:[@"~/Library/Sounds" stringByExpandingTildeInPath]])
	{
		if (![file isEqualToString:@".DS_Store"])
			[soundFiles addObject:[file stringByDeletingPathExtension]];
	}

	for (NSString * file in [fm directoryContentsAtPath:[[NSBundle mainBundle] resourcePath]])
	{
		if ([file hasSuffix:@".m4a"])
			[soundFiles addObject:[file stringByDeletingPathExtension]];
	}
	
	return [[soundFiles allObjects] sortedArrayUsingSelector:@selector(compare:)];
}

- (IBAction) play:(id)sender
{
	[[NSSound soundNamed:[[sender selectedItem] title]] play];
}
	
@end
